<?php

namespace api\modules\v1\controllers;

use backend\models\JjrProjectHouse;
use backend\models\JjrUserBankCard;
use backend\models\JjrUserCommission;
use backend\models\JjrUserWithdraw;
use backend\models\Page;
use yii\base\Exception;
use yii\rest\ActiveController;
use backend\models\JjrUser;
use backend\models\JjrProject;
use backend\models\JjrUserProject;
use backend\models\Picture;
use yii\data\Pagination;
use Yii;
use yii\helpers\Url;
use yii\web\Response;

/**
 * 这里注意是继承 yii\rest\ActiveController 因为源码中已经帮我们实现了index/update等方法
 * 以及其访问规则verbs()等，
 * 其他可参考：http://www.yiichina.com/doc/guide/2.0/rest-controllers
 *
 * 权限采用最简单的QueryParamAuth方式
 * 用户角色权限比较复杂，这里没有做
 *
 * @package api\modules\v1\controllers
 */
class UserController extends ActiveController
{
    public $modelClass = 'backend\models\jjrUser';
//
//    public function behaviors()
//    {
//        $behaviors = parent::behaviors();
//        /* 设置认证方式 */
//        $behaviors['authenticator'] = [
//            'class' => QueryParamAuth::className(),
//        ];
//        return $behaviors;
//    }
    /**
     * 用户登录
     * @param $code
     * @return array
     * @throws Exception
     */
    public function actionLogin($code){
        $appid = env('APP_ID','wx4fdca4f104e73f31');//'wx20b6bf5f34bca65e';
        $secret = env('APP_SECRET','7a5d978522ef177bce51bbfa36fc44a5');//'7a5d978522ef177bce51bbfa36fc44a5';
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $appid . "&secret=" . $secret . "&js_code=" . $code . "&grant_type=authorization_code";
        $info = file_get_contents($url);//发送HTTPs请求并获取返回的数据，推荐使用curl
        $json = json_decode($info);//对json数据解码
        $arr = get_object_vars($json);
      //  print_r($arr);exit;
        if(!isset($arr['openid'])){
            throw new Exception("获取第三方信息失败，请重启小程序再试");
        }
        $openid = $arr['openid'];
        $model = new JjrUser();
        $userInfo = JjrUser::findOne(['openid'=>$openid]);
        if(!$userInfo){
            //$userInfo = ['openid'=>null,'userinfo'=>null];
            return [
                'openid' => $openid,'userInfo'=>null,'clientTotal'=>0,'commission'=>0.00];
        }else{
            //获取客户数和佣金
            $clientTotal = JjrUserProject::find()->where(['jjr_user_id'=>$userInfo->id])->count();
            $commission = JjrUserCommission::find()->where(['jjr_user_id'=>$userInfo->id])->sum('amount');
            return [
                'openid' => $openid,'userInfo'=>$userInfo,'clientTotal'=>$clientTotal,'commission'=>$commission];
        }

    }

    /**
     * 用户绑定
     * @return array
     * @throws Exception
     */
    public function actionBind(){
        $openid = Yii::$app->request->post('openid');
        $mobile = Yii::$app->request->post('mobile');
        $password = Yii::$app->request->post('password');
        $user = JjrUser::findOne(['mobile'=>$mobile,'password'=>$password]);
        if($user){
            if($user->openid!='unset'){
                throw new Exception("用户已被绑定,请勿重复操作");
            }
            $user->updateAttributes(['openid'=>$openid]);
            //获取客户数和佣金
            $clientTotal = JjrUserProject::find()->where(['jjr_user_id'=>$user->id])->count();
            $commission = JjrUserCommission::find()->where(['jjr_user_id'=>$user->id])->sum('amount');
            return [
                'openid' => $openid,'userInfo'=>$user,'clientTotal'=>$clientTotal,'commission'=>$commission];
        }else{
            throw new Exception("用户不存在或密码错误");
        }
    }

    /**
     * 获取用户信息
     * @param $uid
     * @return array
     */
    public function actionGetExtraInfo($uid){
        $clientTotal = JjrUserProject::find()->where(['jjr_user_id'=>$uid])->count();
        $commission = JjrUserCommission::find()->where(['jjr_user_id'=>$uid])->sum('amount');
        return [
           'clientTotal'=>$clientTotal,'commission'=>$commission!=null?$commission:"0.00"];
    }

    /**
     * 查看项目列表
     * @param $code
     * @param string $keyword
     * @return array
     */
    public function actionListProject($code,$keyword="")
    {
         $keyword = trim($keyword);

        $condition = ['p.status' => 1];
        if($code){
            $condition['p.city'] = $code;
        }

        $query = JjrProject::find()->asArray()->alias('p')
            ->select('p.name,p.commission_percent,p.commission_fix,p.commission_type,p.description,p.main_pic,p.id,p.commission_ad,yii2_region.fullname as cityname')
            ->leftJoin('yii2_region','p.city = yii2_region.`code`')
            ->where($condition);
        if($keyword){
            $query->andWhere(['like','p.name',$keyword]);
        }


        $count = $query->count();
        $pagination = new Pagination(['totalCount' => $count]);
        $pagination->pageSizeParam = 'pageSize';
        $pagination->pageParam = 'pageIndex';
        $projects = $query->offset($pagination->offset)
            ->limit($pagination->limit)
            ->orderBy(['commission_type'=>SORT_ASC,'commission_fix'=>SORT_DESC,'commission_percent'=>SORT_DESC])
            ->all();
         foreach ($projects as &$project){
           $pic = Picture::findOne($project['main_pic']);
           $project['main_pic_path'] = Url::to('@storageUrl/image/'.$pic['path'],true);


        }
        return ['pageCount'=>$pagination->pageCount,'projects'=>$projects];
       // return $projects;
    }

    /**
     * 查看城市列表
     * @return array
     * @throws \yii\db\Exception
     */
    public function actionListCity(){
       $ret =  Yii::$app->getDb()->createCommand('SELECT
	yii2_jjr_project.city as code,
	yii2_region.fullname as name
FROM
	yii2_jjr_project
LEFT JOIN yii2_region ON yii2_jjr_project.city = yii2_region.`code` WHERE yii2_jjr_project.status=1
GROUP BY
	yii2_region.`code`')->queryAll();
       return $ret;
    }

    /**
     * 认证经理人
     * @return array
     * @throws Exception
     * @throws \Throwable
     * @throws \yii\db\StaleObjectException
     */
    public function actionIdentification(){
        //Yii::$app->cache->flush();

        $model = new JjrUser();

        if ($model->load(Yii::$app->request->post(),'') ) { //&&$model->save()
            if(!empty($model->invite_code)){
                $user = JjrUser::findOne(['invite_code'=>$model->invite_code]);
                if($user){
                    $model->fuid = $user->id;
                }else{
                    throw  new Exception("邀请码不存在,请重新输入!");
                }
            }
            if($model->save()){
                $model->status = 1; //自动通过审核
                $model->invite_code = str_pad($model->id,4,'0',STR_PAD_LEFT);
                $model->update();
                $userInfo = $model->toArray();
                return ['userInfo'=>$userInfo];
            }else{
                if($model->hasErrors()){
                    throw  new Exception(array_shift($model->getFirstErrors()));
                }
            }

        }else{
            if($model->hasErrors()){
                throw  new Exception(array_shift($model->getFirstErrors()));
             //throw new E
            }
        }
    }


    /**
     * 添加客户
     * @return array
     * @throws Exception
     */
    public function actionAddClient(){
        $model = new JjrUserProject();
        $model->process = JjrUserProject::PROCESS_SIGN_UP;
        $model->status = "1";
        if ($model->load(Yii::$app->request->post(),'') &&$model->save()) {
            return [];
        }else{
            if($model->hasErrors()){
                throw  new Exception(array_shift($model->getFirstErrors()));
                //throw new E
            }
        }
    }

    /**
     * 查看项目
     * @param $projectId
     * @param null $uid
     * @return array
     * @throws Exception
     * @throws \yii\db\Exception
     */
    public function actionViewProject($projectId,$uid=null){
        $sql = 'SELECT
                        p.*,
                        r.fullname
                    FROM
                        yii2_jjr_project p
                    LEFT JOIN yii2_region r ON p.city = r.`code`
                    WHERE
                        p.id = :pid';
        $project = Yii::$app->getDb()->createCommand($sql)->bindParam(":pid",$projectId,\PDO::PARAM_INT)->queryOne();
        if($project==null){
            throw  new Exception("项目不存在");
        }
        $pic = Picture::findOne($project['main_pic']);
        $project['main_pic_path'] = Url::to('@storageUrl/image/'.$pic['path'],true);
        $clientCount = 0;
        if($uid){
           $clientCount =  JjrUserProject::find()->where(['jjr_user_id'=>$uid,'jjr_project_id'=>$projectId])->count();
        }
        //$province =  \common\modelsgii\Region::findOne($project['province']);
        //$city =  \common\modelsgii\Region::findOne($project['city']);
        $project['address'] =  $project['fullname'].$project['address'];
        //获取户型
        $houses = JjrProjectHouse::find()->where(['jjr_project_id'=>$projectId])->asArray()->all();
        foreach ($houses as &$house){
            $pic = Picture::findOne($house['main_pic']);
            $house['main_pic_path'] = Url::to('@storageUrl/image/'.$pic['path'],true);
        }
        return ['project'=>$project,'clientCount'=>$clientCount,'houses'=>$houses];

    }
    public function actionViewProjectHouse($projectId,$houseId){
        //获取户型
        $houses = JjrProjectHouse::find()->where(['jjr_project_id'=>$projectId])->asArray()->all();
        $project = JjrProject::findOne(['id'=>$projectId]);
        $currentHouse = null;
        $otherHouses = [];
        foreach ($houses as $k=>&$house){
            $pic = Picture::findOne($house['main_pic']);
            $house['main_pic_path'] = Url::to('@storageUrl/image/'.$pic['path'],true);
            if($house['id'] ==$houseId){
                $currentHouse = $house;
            }else{
                $otherHouses[] = $house;
            }
        }
        return array('house'=>$currentHouse,'otherHouses'=>$houses,'project'=>$project);
    }

    public function actionViewProjectAlbum($projectId){
           $project =  JjrProject::findOne(['id'=>$projectId]);
            $realPics = $vrPics = $aroundPics  = [];
           if($project){
               $pic = Picture::findOne($project['main_pic']);
               $project['main_pic'] = Url::to('@storageUrl/image/'.$pic['path'],true);
                if(!empty($project['real_pic'])){
                    $realPicIds = explode(',',$project['real_pic']);
                    $realPics = Picture::find()->where(['in','id',$realPicIds])->asArray()->select('path')->all();
                    foreach($realPics as &$pic){
                        $pic['path'] = Url::to('@storageUrl/image/'.$pic['path'],true);
                    }
                }
               if(!empty($project['vr_pic'])){
                   $vrPicIds = explode(',',$project['vr_pic']);
                   $vrPics = Picture::find()->where(['in','id',$vrPicIds])->asArray()->select('path')->all();
                   foreach($vrPics as &$pic){
                       $pic['path'] = Url::to('@storageUrl/image/'.$pic['path'],true);
                   }
               }
               if(!empty($project['around_pic'])){
                   $aroundPicIds = explode(',',$project['around_pic']);
                   $aroundPics = Picture::find()->where(['in','id',$aroundPicIds])->asArray()->select('path')->all();
                   foreach($aroundPics as &$pic){
                       $pic['path'] = Url::to('@storageUrl/image/'.$pic['path'],true);
                   }
               }
               return ['realPics'=>$realPics,'vrPics'=>$vrPics,'aroundPics'=>$aroundPics,'project'=>$project];

           }else{
               throw  new Exception("项目不存在");
           }

    }

    /**
     * 客户查询
     * @param $uid
     * @param int $clientType
     * @param int $clientProjectId
     * @param string $keyword
     * @return array
     */
    public function actionListClient($uid,$clientType=0,$clientProjectId=0,$keyword=""){
        //->all(); ['or like', 'name', ['test', 'sample']]
       $condition = ['jjr_user_id'=>$uid];
       if($clientType){
           $condition['up.process'] = $clientType;
       }
       if($clientProjectId){
           $condition['up.jjr_project_id'] = $clientProjectId;
       }
       $query = JjrUserProject::find()->alias('up')->leftJoin('yii2_jjr_project p','up.jjr_project_id=p.id')
            ->where($condition)
            ->orderBy(['up.update_time'=>SORT_DESC])->asArray();
        if($keyword){
            $query->andFilterWhere(['like', 'up.client_real_name', $keyword]);
            $query->orFilterWhere(['like', 'up.client_mobile', "%{$keyword}",false]);
        }
        $count = $query->count();
        $pagination = new Pagination(['totalCount' => $count]);
        $pagination->pageSizeParam = 'pageSize';
        $pagination->pageParam = 'pageIndex';
        $clients = $query->offset($pagination->offset)
            ->limit($pagination->limit)->select('up.id,up.client_real_name,up.client_mobile,p.name,up.process,up.create_time,up.update_time')
            ->all();

       return ['clients'=>$clients,'pageCount'=>$pagination->pageCount];
    }

    /**
     * 查找客户列表
     * @param $uid
     * @return array
     * @throws \yii\db\Exception
     */
    public function actionListClientProject($uid){
        $ret =  Yii::$app->getDb()->createCommand('SELECT
	up.jjr_project_id id,
	p.name
FROM
	yii2_jjr_user_project up
LEFT JOIN yii2_jjr_project p ON up.jjr_project_id = p.id WHERE up.jjr_user_id=:uid
GROUP BY
	up.jjr_project_id')->bindParam(":uid",$uid,\PDO::PARAM_INT)->queryAll();
        return $ret;
    }

    /**
     * 查看客户详情
     * @param $id
     * @return array|\yii\db\ActiveRecord|null
     */
    public function actionViewClient($id){
        $userProject = JjrUserProject::find()->alias('up')->leftJoin('yii2_jjr_project p','up.jjr_project_id=p.id')
            ->where(['up.id'=>$id])
            ->select('up.id,up.client_real_name,up.client_mobile,p.name,up.adviser,up.adviser_mobile,up.remark,up.process,up.create_time,up.update_time')->asArray()->one();


        return $userProject;

    }


    /**
     * 查看佣金列表
     * @param $uid
     * @param $type
     * @return array
     */
    public function actionListCommission($uid,$type){
        $condition=['uc.jjr_user_id'=>$uid];
        if($type==1){
            $condition['uc.transfer_status'] =1;
        }else if($type==3){
            $condition['uc.transfer_status'] =3;
        }
        $query = JjrUserCommission::find()
            ->alias('uc')
            ->leftJoin('yii2_jjr_user_project up','uc.jjr_user_project_id=up.id')
            ->leftJoin('yii2_jjr_project p','up.jjr_project_id=p.id')
            ->where($condition)
            ->orderBy(['uc.update_time'=>SORT_DESC])->asArray();

        $count = $query->count();
        $pagination = new Pagination(['totalCount' => $count]);
        $pagination->pageSizeParam = 'pageSize';
        $pagination->pageParam = 'pageIndex';

        $commissions = $query->offset($pagination->offset)
            ->limit($pagination->limit)->select('uc.id,p.name,p.update_time,up.client_mobile,up.client_real_name,amount,transfer_status')
            ->all();

        return ['commissions'=>$commissions,'pageCount'=>$pagination->pageCount];
    }

    /**
     * 查看我的银行卡详情
     * @param $uid
     * @param $id
     * @return array|\yii\db\ActiveRecord|null
     */
    public function actionViewBankCard($uid,$id){
        $bankCard = JjrUserBankCard::find()->select('id,jjr_user_id,card_real_name,card_real_name,card_no,card_type,bank_name,bank_branch_name')
                ->where(['jjr_user_id'=>$uid,'id'=>$id])->asArray()->one();
        return $bankCard;
    }

    /**
     * 查看我的银行卡列表
     * @return array
     */
    public function  actionListBankCard(){
        $uid = Yii::$app->request->get('uid');
        $query = JjrUserBankCard::find()->where(['jjr_user_id'=>$uid])->asArray();
        $cards = $query->all();
        return ['cards'=>$cards];

    }

    /**
     * 绑定身份证
     * @return array
     * @throws Exception
     */
    public function actionBindIdcard(){
        $uid = Yii::$app->request->post('uid');
        $user = JjrUser::findOne(['id'=>$uid]);
        if(!$user){
            throw new Exception("用户不存在");
        }
        $user->updateAttributes(['real_name'=>Yii::$app->request->post('real_name'),'idcard'=>Yii::$app->request->post('idcard')]);
        return ['userInfo'=>$user];

    }

    /**
     * 绑定银行卡
     * @return array
     * @throws Exception
     */
    public function actionBindBankCard(){
        //$model = new JjrUserBankCard();
        $id = Yii::$app->request->post('id');
          if($id){
            $model = JjrUserBankCard::findOne($id);
            if($model==null){
                throw  new Exception('记录不存在');
            }
        }else{
            $model = new JjrUserBankCard();
        }

        if ($model->load(Yii::$app->request->post(),'') && $model->save()) {
            return [];
        }else{
            if($model->hasErrors()){
                throw  new Exception(array_shift($model->getFirstErrors()));
            }else{
                throw  new Exception('未知错误');
            }
        }
    }

    /**
     * 查看提现记录
     * @param $uid
     * @return array
     */
    public function  actionListWithdraw($uid){
        $condition=['jjr_user_id'=>$uid];
        $query = JjrUserWithdraw::find()
              ->where($condition)
            ->orderBy(['update_time'=>SORT_DESC])->asArray();
        $count = $query->count();
        $pagination = new Pagination(['totalCount' => $count]);
        $pagination->pageSizeParam = 'pageSize';
        $pagination->pageParam = 'pageIndex';

        $withdraws = $query->offset($pagination->offset)
            ->limit($pagination->limit)->select('bank_name,card_no,amount,create_time,transfer_status')
            ->all();

        return ['withdraws'=>$withdraws,'pageCount'=>$pagination->pageCount];
    }

    /**
     * 申请提现
     * @return array
     * @throws Exception
     */
    public function actionAddWithdraw(){
        $uid = Yii::$app->request->post('uid');
        $id = Yii::$app->request->post('id');
        $userCommissionId = Yii::$app->request->post('userCommissionId');
       $userCommission =  JjrUserCommission::findOne($userCommissionId);
       if($userCommission==null){
           throw  new Exception('记录不存在');
       }
       if($userCommission->jjr_user_id!=$uid){
           throw  new Exception('非法操作');
       }
        $withdraw = JjrUserWithdraw::findOne(['jjr_user_commission_id'=>$userCommissionId,'transfer_status'=>JjrUserWithdraw::TRANSFER_END]);
       if($withdraw){
           throw  new Exception('不能重复提现');
       }
       if($userCommission->transfer_status==1){ //未结佣
           $bankCard = JjrUserBankCard::findOne(['jjr_user_id'=>$uid,'id'=>$id]);
           if(!$bankCard){
               throw  new Exception('银行卡不存在');
           }
           $withdraw = new JjrUserWithdraw();
           $withdraw->jjr_user_id = $uid;
           $withdraw->amount = $userCommission->amount;
           $withdraw->card_no = $bankCard->card_no;
           $withdraw->bank_name = $bankCard->bank_name;
           $withdraw->card_real_name = $bankCard->card_real_name;
           $withdraw->bank_branch_name = $bankCard->bank_branch_name;
           $withdraw->jjr_user_commission_id = $userCommission->id;
           $withdraw->transfer_status = JjrUserWithdraw::TRANSFER_NOT_START; //转账中
           $withdraw->status = 1;
           if($withdraw->save()){
               //更新佣金表
              // $userCommission->transfer_status = 3; //结佣中
               $userCommission->updateAttributes(['transfer_status'=>JjrUserCommission::TRANSFER_STARTED]);
               return [];
           }else{
               if($withdraw->hasErrors()){
                   throw  new Exception(array_shift($withdraw->getFirstErrors()));
               }else{
                   throw  new Exception('未知错误');
               }
           }



       }else{
           throw  new Exception('不能重复提现');
       }

    }

    /**
     * 查看活动规则
     */
    public function actionGetContent($id){
       $page =  Page::findOne(['id'=>$id]);
        header('content-type:text/html;charset=utf-8');
        //\Yii::$app->response->format = \yii\web\Response::FORMAT_HTML;
        echo $page->content;
        exit;
    }

}
